package main

import (
	"context"
	"flag"
	"fmt"
	"github.com/tencentyun/cos-go-sdk-v5"
	"net/http"
	"net/url"
	"path"
	"strconv"
	"strings"
	"time"
)

func makeClient(appId string, secretId string, secretKey string, bucketName string, region string) (*cos.Client, string) {

	bucketUrl := fmt.Sprintf("https://%s-%s.cos.%s.myqcloud.com", bucketName, appId, region)
	endpointUrl, _ := url.Parse(bucketUrl)

	client := cos.NewClient(&cos.BaseURL{
		BucketURL: endpointUrl,
	}, &http.Client{
		Transport: &cos.AuthorizationTransport{
			SecretID:  secretId,
			SecretKey: secretKey,
		},
	})

	return client, bucketUrl
}

func check(appId string, secretId string, secretKey string, bucketName string, region string) (string, bool) {

	if len(appId) == 0 {
		return "请检查 App Id", true
	}
	if len(secretId) == 0 {
		return "请检查 Secret Id", true
	}
	if len(secretKey) == 0 {
		return "请检查 Secret Key", true
	}
	if len(bucketName) == 0 {
		return "请检查 Bucket Name", true
	}
	if len(region) == 0 {
		return "请检查 Region", true
	}

	return "", false
}

func main() {

	var appId,secretId, secretKey, bucketName, region, bindDomain string

	flag.StringVar(&appId, "appId", "", "腾讯云存储的 app id")
	flag.StringVar(&secretId, "secretId", "", "腾讯云存储的 API 访问秘钥： secret id")
	flag.StringVar(&secretKey, "secretKey", "", "腾讯云存储的 API 访问秘钥： secret key")
	flag.StringVar(&bucketName, "bucketName", "", "腾讯云存储对应的 bucket name")
	flag.StringVar(&region, "region", "", "请填写区域，如： ap-guangzhou")
	flag.StringVar(&bindDomain, "bindDomain", "", "如果有绑定域名CDN，可以填写，格式为 https://xxx.com")

	flag.Parse()

	files := flag.Args()

	appId = strings.TrimSpace(appId)
	secretId = strings.TrimSpace(secretId)
	secretKey = strings.TrimSpace(secretKey)
	bucketName = strings.TrimSpace(bucketName)
	region = strings.TrimSpace(region)
	bindDomain = strings.TrimSpace(bindDomain)

	if errMsg, err := check(appId, secretId, secretKey, bucketName, region); err {
		fmt.Println(errMsg)
		return
	}

	client, urlBase := makeClient(appId, secretId, secretKey, bucketName, region)

	if bindDomain != "" {
		urlBase = bindDomain
	}

	uploadedFiles := make([]string, 0)
	for _, file := range files {

		fileTimeString := time.Now().Format("2006-01-02-03-04-05")
		filename := fmt.Sprintf("%s-%s%s", fileTimeString, strconv.FormatInt(time.Now().UnixNano(), 12), path.Ext(file))

		_, err := client.Object.PutFromFile(context.Background(), filename, file, nil)
		if err != nil {
			fmt.Println(err)
			return
		}

		uploadedFiles = append(uploadedFiles, filename)
	}

	fmt.Println("Upload Success:")
	for _, filename := range uploadedFiles {
		fmt.Printf("%s/%s\n", urlBase, filename)
	}
}
